package com.queue.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.queue.model.QueueMessage;
import com.queue.service.QueueService;
import org.springframework.web.socket.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

public class QueueWebSocketHandler implements WebSocketHandler {
    private final QueueService queueService = new QueueService();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接建立: " + session.getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String payload = message.getPayload().toString();
        QueueMessage queueMessage = objectMapper.readValue(payload, QueueMessage.class);
        
        String clientId = queueMessage.getClientId();
        sessions.put(clientId, session);

        switch (queueMessage.getType()) {
            case "JOIN_QUEUE":
                handleJoinQueue(clientId);
                break;
            case "LEAVE_QUEUE":
                handleLeaveQueue(clientId);
                break;
            case "GET_STATUS":
                sendStatus(clientId);
                break;
        }
    }

    private void handleJoinQueue(String clientId) throws Exception {
        boolean canStart = queueService.joinQueue(clientId);
        
        if (canStart) {
            sendMessage(clientId, "CAN_START", "可以开始选号");
        } else {
            int position = queueService.getQueuePosition(clientId);
            sendMessage(clientId, "WAITING", "排队中，前面还有 " + (position - 1) + " 人");
        }
        
        broadcastQueueUpdate();
    }

    private void handleLeaveQueue(String clientId) throws Exception {
        queueService.leaveQueue(clientId);
        sendMessage(clientId, "LEFT_QUEUE", "已离开队列");
        broadcastQueueUpdate();
    }

    private void sendStatus(String clientId) throws Exception {
        if (queueService.isActive(clientId)) {
            sendMessage(clientId, "CAN_START", "可以开始选号");
        } else {
            int position = queueService.getQueuePosition(clientId);
            if (position > 0) {
                sendMessage(clientId, "WAITING", "排队中，前面还有 " + (position - 1) + " 人");
            } else {
                sendMessage(clientId, "NOT_IN_QUEUE", "未在队列中");
            }
        }
    }

    private void sendMessage(String clientId, String type, String message) throws Exception {
        WebSocketSession session = sessions.get(clientId);
        if (session != null && session.isOpen()) {
            QueueMessage response = new QueueMessage(type, clientId);
            response.setMessage(message);
            response.setPosition(queueService.getQueuePosition(clientId));
            response.setActiveCount(queueService.getActiveCount());
            
            String json = objectMapper.writeValueAsString(response);
            session.sendMessage(new TextMessage(json));
        }
    }

    private void broadcastQueueUpdate() throws Exception {
        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            String clientId = entry.getKey();
            WebSocketSession session = entry.getValue();
            
            if (session.isOpen()) {
                if (queueService.isActive(clientId)) {
                    sendMessage(clientId, "CAN_START", "可以开始选号");
                } else {
                    int position = queueService.getQueuePosition(clientId);
                    if (position > 0) {
                        sendMessage(clientId, "WAITING", "排队中，前面还有 " + (position - 1) + " 人");
                    }
                }
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("传输错误: " + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String clientId = null;
        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            if (entry.getValue().equals(session)) {
                clientId = entry.getKey();
                break;
            }
        }
        
        if (clientId != null) {
            sessions.remove(clientId);
            queueService.leaveQueue(clientId);
            broadcastQueueUpdate();
        }
        
        System.out.println("连接关闭: " + session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}